package cn.stylefeng.guns.modular.demos.util;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
 
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import com.alibaba.fastjson.JSONObject;
 
/**
 * Http请求工具类,发送json返回json
 * 
 * 除了要导入json-lib-2.1.jar之外，还必须有其它几个依赖包：
 * commons-beanutils.jar
 * commons-httpclient.jar
 * commons-lang.jar
 * ezmorph.jar
 * morph-1.0.1.jar
 * 另外，commons-collections.jar也需要导入
 */
@SuppressWarnings("deprecation")
public class HttpRequestUtil {
    
    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);  
    
    public static final int cache = 10 * 1024;
    public static final boolean isWindows;
    public static final String splash;
    public static final String root;
 
    static {
        if (System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("windows")) {
            isWindows = true;
            splash = "\\";
            root = "D:\\data";
        } else {
            isWindows = false;
            splash = "/";
            root = "/search";
        }
    }
 
    /**
     * 发送get请求
     * @param url 路径
     * @return
     */
    @SuppressWarnings("resource")
    public static JSONObject httpGet(String url){
        
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
 
            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(strResult);
               
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return jsonResult;
    }
    
    
    /**
     * 发送get请求
     * @param url 路径
     * @return
     */
    @SuppressWarnings("resource")
    public static String httpGet2(String url){
        
        //get请求返回结果
    	String strResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
 
            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                strResult = EntityUtils.toString(response.getEntity());
                //url = URLDecoder.decode(url, "UTF-8");
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return strResult;
    }
    
    /**
     * httpPost
     * @param url  路径
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url,JSONObject jsonParam){
        return httpJsonPost(url, jsonParam, false);
    }
 
    /**
     * post请求
     * @param url         url地址
     * @param jsonParam     参数
     * @param noNeedResponse    不需要返回结果
     * @return
     */
    public static JSONObject httpJsonPost(String url,JSONObject jsonParam, boolean noNeedResponse){
        
        //post请求返回结果
        @SuppressWarnings("deprecation")
        
        BasicHttpParams httpParams = new BasicHttpParams();  
        HttpConnectionParams.setConnectionTimeout(httpParams, 7000);
        HttpConnectionParams.setSoTimeout(httpParams, 7000);
        
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        }
        return jsonResult;
    }
    
    /**
     * post请求
     * @param url         url地址
     * @param jsonParam     参数
     * @param noNeedResponse    不需要返回结果
     * @return
     */
    public static String httpPost(String url,String param){
        
        //post请求返回结果
        @SuppressWarnings("deprecation")
        
        BasicHttpParams httpParams = new BasicHttpParams();  
        HttpConnectionParams.setConnectionTimeout(httpParams, 7000);
        HttpConnectionParams.setSoTimeout(httpParams, 7000);
        
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        String rspstr = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != param) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(param, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
               
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    rspstr = EntityUtils.toString(result.getEntity());
                    //rspstr = inputStreamToString(result.getEntity().getContent());
                    return rspstr;
                } catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        }
        return rspstr;
    }
    
    public static String httpPost(String url){
        return httpPost(url,"");
    }
    
    /**
     * 获取response要下载的文件的默认路径
     *
     * @param response
     * @return
     */
    public static String getFilePath(HttpResponse response) {
        String filepath = root + splash;
        String filename = getFileName(response);
 
        if (filename != null) {
            filepath += filename;
        } else {
            filepath += getRandomFileName();
        }
        return filepath;
    }
    
    /**
     * 获取response header中Content-Disposition中的filename值
     *
     * @param response
     * @return
     */
    public static String getFileName(HttpResponse response) {
        Header contentHeader = response.getFirstHeader("Content-Disposition");
        String filename = null;
        if (contentHeader != null) {
            HeaderElement[] values = contentHeader.getElements();
            if (values.length == 1) {
                NameValuePair param = values[0].getParameterByName("filename");
                if (param != null) {
                    try {
                        //filename = new String(param.getValue().toString().getBytes(), "utf-8");
                        //filename=URLDecoder.decode(param.getValue(),"utf-8");
                        filename = param.getValue();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return filename;
    }
 
    /**
     * 获取随机文件名
     *
     * @return
     */
    public static String getRandomFileName() {
        return String.valueOf(System.currentTimeMillis());
    }
 
    public static void outHeaders(HttpResponse response) {
        Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
    }
 
 
    /**
     * 根据url下载文件，文件名从response header头中获取
     *
     * @param url
     * @return
     */
    public static int download(String url) {
        return getDownload(url, null);
    }
 
    /**
     * 根据url下载文件，保存到filepath中
     *
     * @param url
     * @param filepath
     * @return
     */
    public static int getDownload(String url,String filepath){
         try {
             HttpClient client = HttpClients.createDefault();
             HttpGet httpget = new HttpGet(url);
             HttpResponse response = client.execute(httpget);
 
             HttpEntity entity = response.getEntity();
             InputStream is = entity.getContent();
             if (filepath == null){
                 filepath = getFilePath(response);
             }
 
             File file = new File(filepath);
             file.getParentFile().mkdirs();
             FileOutputStream fileout = new FileOutputStream(file);
             /**
              * 根据实际运行效果 设置缓冲区大小
              */
             byte[] buffer = new byte[cache];
             int ch = 0;
             while ((ch = is.read(buffer)) != -1) {
                 fileout.write(buffer, 0, ch);
             }
             is.close();
             fileout.flush();
             fileout.close();
 
             return 0;
         } catch (Exception e) {
             e.printStackTrace();
         }
         return -1;
    }
    
}